package com.pokermind.dse.tcp.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.pokermind.common.util.JsonUtil;
import com.pokermind.dse.tcp.protocol.ProtocolConstants;
import com.pokermind.dse.tcp.protocol.ProtocolMessage;
import com.pokermind.dse.tcp.util.ResponseWrapper;
import com.pokermind.model.dto.AIAnalysisRequest;
import com.pokermind.model.dto.AIAnalysisResponse;
import com.pokermind.model.dto.SimpleAIDecision;
import com.pokermind.operator.AIAnalysisOperator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import jakarta.annotation.PostConstruct;

/**
 * AI Analysis Service
 * AI分析服务，处理TCP协议的AI分析业务
 * 
 * 支持的协议：
 * - AI_ANALYZE_REQ (2001) - AI分析请求
 * 
 * 与HTTP服务共享业务逻辑，通过AIAnalysisOperator处理
 * 
 * @author PokerMind Team
 */
@Service
public class AIAnalysisService {

    private static final Logger logger = LoggerFactory.getLogger(AIAnalysisService.class);

    @Autowired
    private AIAnalysisOperator aiAnalysisOperator;
    
    @Autowired
    private com.pokermind.repository.dao.PokerHandDao pokerHandDao;

    private final ObjectMapper objectMapper = new ObjectMapper();

    @PostConstruct
    public void initialize() {
        logger.info("AIAnalysisService initialized");
    }

    /**
     * 处理AI分析协议消息
     */
    public ProtocolMessage processMessage(ProtocolMessage message) {
        short protocolId = message.getProtocolId();
        
        if (logger.isDebugEnabled()) {
            logger.debug("Processing AI analysis message: {} from {}", 
                    message.getProtocolName(), message.getClientId());
        }

        try {
            switch (protocolId) {
                case ProtocolConstants.AI_ANALYZE_REQ:
                    return handleAIAnalysis(message);
                default:
                    logger.warn("Unsupported AI analysis protocol: {} from {}", 
                            message.getProtocolName(), message.getClientId());
                    return ProtocolMessage.createErrorResponse(message, 400, "Unsupported protocol");
            }
        } catch (Exception e) {
            logger.error("Error processing AI analysis message {}: {}", 
                    message.getProtocolName(), e.getMessage(), e);
            return ProtocolMessage.createBusinessErrorResponse(message, 
                    "AI analysis processing error", e.getMessage());
        }
    }

    /**
     * 处理AI分析请求
     */
    private ProtocolMessage handleAIAnalysis(ProtocolMessage message) throws Exception {
        try {
            // 设置 RequestContext（贯穿整个调用链）
            String requestId = ResponseWrapper.extractClientRequestId(message);
            String connectionId = extractClientConnectionId(message);
            
            if (requestId != null && !requestId.isEmpty()) {
                com.pokermind.common.context.RequestContext.setRequestId(requestId);
            }
            
            if (connectionId != null && !connectionId.isEmpty()) {
                com.pokermind.common.context.RequestContext.setConnectionId(connectionId);
            }
            
            // V4.7: 设置请求内容（不格式化，保持单行）
            String requestContent = message.getJsonBody();
            if (requestContent != null) {
                com.pokermind.common.context.RequestContext.setRequestContent(requestContent);
            }
            
            // 使用统一的数据提取方式（和其他服务保持一致）
            AIAnalysisRequest request = ResponseWrapper.extractBusinessData(message, AIAnalysisRequest.class);
            
            // 验证请求参数（V4.1更新）
            if (request.getHandId() == null) {
                throw new IllegalArgumentException("hand_id is required");
            }
            
            if (request.getPlayerId() == null || request.getPlayerId().trim().isEmpty()) {
                throw new IllegalArgumentException("player_id is required");
            }
            
            // V4.7: 根据non-hero perspective架构，hole_cards为可选字段
            // 后端可基于公共信息（位置、筹码、底池、行动历史等）进行分析
            // 如果客户端提供hole_cards，则进行更精确的分析
            
            // 调用业务逻辑（获取完整分析响应）
            AIAnalysisResponse fullResponse = aiAnalysisOperator.performAIAnalysis(request);
            
            // V4.10: 直接返回完整的 AI 分析响应（包含 GTO、AI、equity 等）
            // 不再转换为简化版本，客户端需要完整数据
            return ResponseWrapper.createSuccessResponse(message, "success", fullResponse);
        } finally {
            // 清理 RequestContext
            com.pokermind.common.context.RequestContext.clear();
        }
    }

    /**
     * 从playersInfo JSON中提取玩家位置（V4.1新增）
     */
    private String extractPlayerPosition(com.pokermind.model.po.PokerHand hand, String playerId) {
        if (hand == null || playerId == null) {
            return null;
        }
        
        try {
            String playersInfoJson = hand.getPlayersInfo();
            if (playersInfoJson == null || playersInfoJson.isEmpty()) {
                return null;
            }
            
            com.fasterxml.jackson.databind.JsonNode playersArray = objectMapper.readTree(playersInfoJson);
            if (!playersArray.isArray()) {
                return null;
            }
            
            for (com.fasterxml.jackson.databind.JsonNode playerNode : playersArray) {
                String nodePlayerId = playerNode.path("player_id").asText();
                if (playerId.equals(nodePlayerId)) {
                    return playerNode.path("position").asText();
                }
            }
        } catch (Exception e) {
            logger.warn("Failed to extract player position for player: {}", playerId, e);
        }
        return null;
    }
    
    /**
     * 从请求消息中提取客户端连接ID
     */
    private String extractClientConnectionId(ProtocolMessage message) {
        try {
            if (message.getJsonNode() != null && message.getJsonNode().has("connId")) {
                return message.getJsonNode().get("connId").asText();
            }
        } catch (Exception e) {
            logger.debug("Failed to extract connId from message: {}", e.getMessage());
        }
        return null;
    }

    /**
     * 解析JSON到对象
     */
    private <T> T parseJsonToObject(String json, Class<T> clazz) throws Exception {
        try {
            return objectMapper.readValue(json, clazz);
        } catch (Exception e) {
            logger.error("Failed to parse JSON to {}: {}", clazz.getSimpleName(), e.getMessage());
            throw new IllegalArgumentException("Invalid JSON format for " + clazz.getSimpleName());
        }
    }
}
